/*
 * 表格渲染
 * @Author: mikey.zhaopeng
 * @Date:   2016-05-05 10:58:02
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 16:12:20
 */

'use strict';
define([
    '../../framework/base/baseView',
    '../../framework/bean/ecReport'
], function(
    BaseView,
    ecReportModel
) {
    function me() {
        BaseView.apply(this, arguments);
        var self = this;
        this.groups = ["ecTemplateMateriel","billingEvent","optimizationGoal","placement","bid","audienceManager","productSet"];
        this.init = function(feedId) {
            self.$root = $('#adTest-table');
            self.event();
        }
        this.render = function() {
            self.$table = self.$root.find('table');
            self.$thead = self.$root.find('thead');
            self.$tbody = self.$root.find('tbody');
        }

        this.event = function() {
            $(".table-summary-single").off("click").on("click", function(e){
                $(".table-summary-single").removeClass("s-active");
                $(this).addClass("s-active");
                var _v = $(this).attr("value");
                if (_v == 1){
                    self.params.timeIncrement = 1;
                } else {
                    self.params.timeIncrement = "";
                }
                self.params.cPage = 1;
                console.log(self.params)
                self.renderTable(self.params, true);
            });
        }

        this.renderTable = function(params, _isInit) {
            if (_.isUndefined(params.cPage)) {
                params.cPage = 1;
            }
            if (_.isUndefined(params.pSize)) {
                params.pSize = 20;
            }
            if (_.isUndefined(params.timeIncrement)) {
                params.timeIncrement = 1;
            }

            self.params = params;

            ecReportModel.report2(params, function(results) {
                console.log(results)
                $(".table-summary-single").removeClass("s-active");
                if (params.timeIncrement && params.timeIncrement == 1){
                    $('button.table-summary-single[value="1"]').addClass("s-active");
                } else {
                    $('button.table-summary-single[value="-1"]').addClass("s-active");
                }

                $(".table-container").removeClass("hide");
                if (self.kit.isBlank(results) || self.kit.isEmptyObject(results)){
                    //显示无数据
                    $(".no-result",".table-container").show();
                    $(".table-content",".table-container").hide();
                    return;
                } else {
                    //显示列表
                    $(".no-result",".table-container").hide();
                    $(".table-content",".table-container").show();
                }


                if (_isInit){
                    //每次点击查询按钮需要重新渲染列表
                    self._renderHeader(params, results);
                    self._renderTbody(params, results);
                    self._initListManager(params, results);
                }
                else {
                    self._renderTbody(params, results);
                }

                self._renderListManager(params, results);
            });
        }

        this._initListManager = function(params, results){
            var filters = {};
            var _processedFilters = [];
            $.each(results.summary[params.group], function(i, _filter){
                _processedFilters.push({
                    id : _filter,
                    text : self.kit.translate("abTest", _filter)
                })
            })
            filters[params.group] = _processedFilters;
            $('table[list-manager="adTest"]').listManager('init', {
                setTopVal: 301 + $(".query-result-area").height(), //调整吸顶的高度,需要减去这个高度
                scrollDOM: $('.fmp-article'), //监听滚动条
                supportAjaxPage: true,
                initCleanCache : true,
                disableCache: false,
                filters : filters,
                pageCallback: function(query) {
                    if (!((query.cPage * 1 == self.params.cPage * 1) && (query.pSize * 1 == self.params.pSize * 1))) {
                        var queryParams = $.extend(self.params, query);
                        self.renderTable(queryParams);
                    }
                }
            });
        }

        this._renderTbody = function(params, results) {
            var header = self.headerColumn(params, results).colKey;
            self.$tbody.empty();
            _.each(results.list, function(v) {
                var t = '<tr>';
                t = t + '<td>' + v.day + '</td>'; //日期
                _.each(header, function(col) {
                    var val = v[col];
                    t = t + '<td filter="' + val + '">' + self._formatData(col, val) + '</td>';
                });
                t = t + '</tr>';
                self.$tbody.append(t);
            });
            $(window).trigger('resize');
        }

        this._renderHeader = function(params, results) {
            self.$root.html('<table class="smart-form" list-manager="adTest"> <thead> </thead> <tbody> </tbody> </table>');
            self.$table = self.$root.find('table');
            self.$thead = self.$root.find('thead');
            self.$tbody = self.$root.find('tbody');
            self.$thead.empty();
            var header = self.headerColumn(params, results).cols;
            var t = '<tr>';
            t = t + '<th data-col="day" th-name="day">' + I18N.getText('abTest', 'day') + '&nbsp;&nbsp;&nbsp;&nbsp;</th>';
            _.each(header, function(v) {
                var _filter = "";
                if (params.group == v){
                    _filter = 'th-filter="1"';
                }
                t = t + '<th data-col="' + v + '" th-name="' + v + '" ' + _filter+ '>' + I18N.getText('abTest', v) + '</th>';
            });
            t = t + '</tr>';
            self.$thead.html(t);
        }


        this._renderListManager = function(params, results) {
            if (results.summary) {
                var tPage = self.culTotalPageNum(results.summary.count, params.pSize);
                var pageParams = { tPage: tPage, cPage: params.cPage, pSize: params.pSize, tSize: results.summary.count };
                $('table[list-manager="adTest"]').listManager([{'resetTd':false, 'resetPageData': pageParams}]);
            }
        }

        this.resetListManagerSetTopVal = function(){
            if ($('table[list-manager="adTest"]').length){
                //根据背景维度的增删，修改表格的悬浮情况
                var _setTopVal = 301 + $(".query-result-area").height();
                $('table[list-manager="adTest"]').listManager([{'resetSetTopVal':_setTopVal}]);
                var _lm = $('table[list-manager="adTest"]').data( 'listManager')
                $(_lm.scrollDOM).trigger('scroll');
            }
        }

        /**
         * { 列显示分组字典 }
         */
        this.headerColumn = function(params, results) {
            var header = [
                "impressions",
                "clicks",
                "ctr",
                "costPerClick",
                "spend",
                "budget",
                "cart",
                "cartR",
                "costPerCart",
                "purchase",
                "salesAmount",
                "purchaseR",
                "roi",
                "costPerPurchase",
                "frequency"
            ];
            if (params.group == 'placement') {
                header = _.filter(header, function(col) { //如果根据版位分组,则不显示预算
                    return col != 'placement';
                });
            }
            header = [params.group].concat(header); //将group放到头部
            var newHeader = []; //带分类的
            _.each(header, function(col) {
                newHeader.push(col);
            });
            return {
                cols: newHeader, //列名显示
                colKey: header //  从result取的key
            };
        }


        this._formatData = function(col, val) {
            if (_.isUndefined(val)) {
                return '-';
            }

            if (this.groups.indexOf(col) != -1){
                return self.kit.translate("abTest", val);
            }

            if (col == 'ctr' || col == 'cartR' || col == 'purchaseR') {
                return self.kit.percentage(val);
            }
            if (col == 'roi') {
                val = val || 0;
                return (val * 1).toFixed(2);
            }
            if (col == 'costPerClick' || col == 'spend' || col == 'budget' || col == 'costPerCart' || col == 'salesAmount' || col == 'costPerPurchase') {
                return '$ ' + self.kit.cent_to_dollar(val);
            }

            if (col == 'frequency') {
                return Number(val).toFixed(2);
            }
            return val;
        }

        this.destroy = function() {
            self.$root.empty();
        }

    }
    return me;
});
